import csv
import json
import os

def get_application_and_viewpoint(ip):
    """Determine application and viewpoint based on last digit of IP."""
    try:
        last_part = ip.strip().split('.')[-1]
        last_digit = int(last_part)%10
    except (ValueError, IndexError):
        # Fallback if IP format is unexpected
        return "EOL", ""

    if 1 <= last_digit <= 4:
        return "EOL", f"Side {last_digit}"
    elif last_digit == 5:
        return "EOL", "Front"
    elif last_digit == 7:
        return "IMLA", "Top"
    elif last_digit == 8:
        return "IMLA", "Bottom"
    else:
        # Keep defaults or leave viewpoint empty for other digits
        return "", ""

def load_cameras_from_csv(csv_file_path):
    cameras = []

    with open(csv_file_path, mode='r', newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        
        for row in reader:
            model = row.get("Model", "").strip()
            ip = row.get("IP in Mezzanine", "").strip()
            factory = row.get("Factory", "").strip()

            # Skip if required fields are missing
            if not model or not ip:
                continue

            if model == "OV80i" and ip:
                # Determine application and viewpoint from IP
                application, viewpoint = get_application_and_viewpoint(ip)

                camera = {
                    "application": application,
                    "factory": factory,
                    "ip": ip,
                    # "line": row.get("Line", "0").strip(),
                    "line": 0,
                    "model": "OV80i",
                    "product": row.get("Product", "Leg").strip(),
                    "viewpoint": viewpoint
                }
                cameras.append(camera)

    return {
        "cameras": cameras
    }

# Example usage
if __name__ == "__main__":
    csv_path = r"C:\overview\applications\overview\global_dashboard\cameras.csv"
    output_path = r"C:\overview\applications\overview\global_dashboard\cameras_output.json"

    result = load_cameras_from_csv(csv_path)
    
    # Save to JSON file
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=2)

    print(f"Data saved to: {output_path}")